<template>
	<page-meta :page-style="'overflow:' + (showPopup ? 'hidden' : 'visible')"></page-meta>
	<view class="container">
		<uni-nav-bar title="录入商品信息" fixed statusBar :border="false" leftIcon='back'
			@clickLeft="goBackPage"></uni-nav-bar>
		<text class="tip">
			Tip：在此录入商品信息，并对商品进行分类，如需新增分类信息
			<text class="tip-link" @click="gotoTypePage">点此前往</text>
		</text>
		<TypeList :activeTypeCard="activeTypeCard" :activeTag="activeTag" :datas="datas" :goodsData="goodsData"
			:handleTypeCard="handleTypeCard" :handleTag="handleTag" :handleClick="editCard" type='ADD'>
			<template #addCard v-if="datas?.find(val => val._id === activeTypeCard)?.children?.length">
				<view class="addCard">
					<view class="addCard-info" hover-class="addCard-infoActive" hover-stay-time="100" @click="addCard">
						<uni-icons type="cloud-upload" size="26" color="#297ff6"></uni-icons>
						<text class="addCard-info-text">点此新增</text>
					</view>
				</view>
			</template>
		</TypeList>

		<uni-popup ref="delDialog" type="dialog">
			<uni-popup-dialog type="error" cancelText="取消" confirmText="确定" title="危险操作提示"
				:content="`确定要删除“${popupFormData.name}”吗？`" @confirm="delConfirm" @close="cancleDel" />
		</uni-popup>

		<uni-popup class="popup" ref="selectPopup" safeArea backgroundColor="#fff" borderRadius="6px 6px 0 0"
			@maskClick="changeShowPopup">
			<uni-forms ref="popupForm" :model="popupFormData">
				<view class="popup-options">
					<text class="popup-btn popup-btn-danger" v-if="popupFormData.optType === 'edit'"
						@click="delPopup">删除</text>
					<text class="popup-title">{{popupFormData.optType === 'edit' ? '编辑' : '新增'}}商品</text>
					<text class="popup-btn popup-btn-primary" @click="savePopup">保存</text>
				</view>
				<view class="popup-content">
					<uni-forms-item label="名称" name="name" :rules="[{required: true, errorMessage: '请输入名称'}]">
						<uni-easyinput v-model="popupFormData.name" placeholder="请输入" trim />
					</uni-forms-item>
					<uni-forms-item label="售价" name="goods_sale">
						<uni-easyinput type="digit" v-model="popupFormData.goods_sale" placeholder="请输入" trim />
					</uni-forms-item>
					<uni-forms-item label="内容" name="goods_desc">
						<uni-easyinput type="textarea" v-model="popupFormData.goods_desc" autoHeight trim />
					</uni-forms-item>
					<uni-forms-item label="缩略图" name="goods_thumb">
						<uni-file-picker v-model='popupFormData.goods_thumb' return-type='object'></uni-file-picker>
					</uni-forms-item>
					<uni-forms-item label="图片路径" name="goods_banner_imgs">
						<uni-file-picker v-model='popupFormData.goods_banner_imgs' :limit="9"></uni-file-picker>
					</uni-forms-item>
				</view>
			</uni-forms>
		</uni-popup>

		<to-top :isShow="isShowTop" :right="30" :bottom="80"></to-top>
	</view>
</template>

<script setup>
	import {
		getCurrentInstance,
		reactive,
		ref
	} from 'vue';
	import {
		mockData
	} from '/pages/type/mock.js';
	import {
		onShow,
		onPullDownRefresh,
		onPageScroll
	} from '@dcloudio/uni-app'
	import TypeList from '/pages/type/components/typeList/index.vue'

	const {
		proxy
	} = getCurrentInstance()

	const activeTypeCard = ref('')
	const activeTag = ref('')
	const datas = ref([])
	const goodsData = ref([])
	const showPopup = ref(false)
	const isShowTop = ref(false)
	let popupFormData = reactive({})

	const loadingOptions = {
		loadingOptions: {
			title: '加载中...',
			mask: true
		},
		errorOptions: {
			type: 'toast'
		}
	}

	const goBackPage = () => uni.navigateBack()

	const gotoTypePage = () => uni.redirectTo({
		url: '/pages/admin/components/typeInfo/index'
	})

	// const imgProgress = (e) => {
	// 	const {
	// 		tempFiles
	// 	} = e
	// 	let compressImg = []
	// 	tempFiles.map(item => {
	// 		const {
	// 			size,
	// 			path
	// 		} = item
	// 		if (size > 524288) {
	// 			uni.compressImage({
	// 				src: path,
	// 				quality: 50,
	// 				width: "500px",
	// 				height: "auto",
	// 				compressedWidth: "300px",
	// 				success(res) {
	// 					console.log(JSON.stringify(res))
	// 				},
	// 				fail(err) {
	// 					console.log(err)
	// 				}
	// 			})
	// 		}
	// 	})
	// }

	const handleTypeCard = (id) => {
		if (id !== activeTypeCard.value) {
			activeTypeCard.value = id
			activeTag.value = datas.value.find(val => val._id === id)?.children?.[0]?._id
			getGoodsData()
		}
	}

	const handleTag = (id) => {
		if (id !== activeTag.value) {
			activeTag.value = id
			getGoodsData()
		}
	}

	const clearEvent = () => {
		proxy.$refs.selectPopup.close()
		proxy.$refs.popupForm.clearValidate()
		showPopup.value = false
		setTimeout(() => popupFormData = reactive({}), 300)
	}

	const addCard = () => {
		popupFormData = reactive({
			optType: 'add'
		})
		proxy.$refs.selectPopup.open('bottom')
		showPopup.value = true
	}

	const editCard = (item) => {
		popupFormData = reactive({
			...item,
			optType: 'edit'
		})
		proxy.$refs.selectPopup.open('bottom')
		showPopup.value = true
	}

	// 监听 Popup 弹窗状态改变
	const changeShowPopup = (e) => {
		clearEvent()
	}

	const delConfirm = async (_id = popupFormData._id) => {
		const mallGoods = uniCloud.importObject('mall-goods')
		try {
			await mallGoods.deleteData(_id)
			uni.showToast({
				title: '删除成功',
				icon: 'success'
			})
			getGoodsData({
				customUI: true
			})
			clearEvent()
		} catch (err) {
			console.log('错误 ', err.errCode, '：', err.errMsg, 'Json：', err)
		}
	}

	const cancleDel = () => {
		proxy.$refs.selectPopup.open('bottom')
	}

	const delPopup = () => {
		proxy.$refs.delDialog.open()
		proxy.$refs.selectPopup.close()
	}

	const savePopup = () => {
		proxy.$refs.popupForm.validate(async (err, formData) => {
			if (!err) {
				const mallGoods = uniCloud.importObject('mall-goods')
				try {
					switch (popupFormData.optType) {
						case 'add':
							await mallGoods.addData({
								...formData,
								category_id: activeTag.value,
								category_parent_id: activeTypeCard.value
							})
							break;
						case 'edit':
							if (popupFormData?.optType) {
								delete popupFormData.optType
							}
							await mallGoods.updateData({
								_id: popupFormData._id,
								data: popupFormData
							})
							break;
						default:
							break;
					}
					uni.showToast({
						title: `保存成功`
					})
					getGoodsData({
						customUI: true
					})
					clearEvent()
				} catch (err) {
					console.log('错误 ', err.errCode, '：', err.errMsg, 'Json：', err)
				}
			}
		})
	}

	const getGoodsData = async (options = loadingOptions, category_id = activeTag.value) => {
		const mallGoods = uniCloud.importObject('mall-goods', options)
		try {
			const res = await mallGoods.getData(category_id)
			goodsData.value = res?.data
		} catch (err) {
			console.log('错误 ', err.errCode, '：', err.errMsg, 'Json：', err)
		}
		uni.stopPullDownRefresh()
	}

	const getCategoriesData = async (options = loadingOptions) => {
		const mallCategories = uniCloud.importObject('mall-categories', options)
		try {
			const res = await mallCategories.getData()
			datas.value = res.data

			if (!activeTypeCard.value && !activeTag.value) {
				const typeId = res.data[0]?._id
				activeTypeCard.value = typeId
				activeTag.value = res.data.find(val => val._id === typeId)?.children?.[0]?._id
			}

			getGoodsData()
		} catch (err) {
			uni.stopPullDownRefresh()
			console.log('错误 ', err.errCode, '：', err.errMsg)
		}
	}

	onPageScroll(e => {
		if (e.scrollTop > 200) {
			isShowTop.value = true
		} else {
			isShowTop.value = false
		}
	})
	onPullDownRefresh(() => getCategoriesData())
	onShow(() => {
		getCategoriesData()
	})
</script>

<style lang="scss" scoped>
	@import url("/styles/common.scss");

	.container {
		-webkit-overflow-scrolling: touch;
	}

	.tip {
		display: block;
		font-size: 14px;
		text-indent: 2em;
		color: #666;
		background-color: var(--background-color);
		box-shadow: inset 0 2px 6px 0 rgba(0, 0, 0, 0.04);
		line-height: 24px;
		padding: 6px 16px;
		border-top: 1px solid #eee;
		border-bottom: 1px solid #eee;

		&-link {
			color: #54a1ff;
			text-decoration: underline;
		}
	}

	.addCard {
		display: flex;
		align-items: center;
		justify-content: center;
		box-sizing: border-box;

		&-info {
			width: 26vw;
			height: 26vw;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			background-color: #f0f9ff;
			border: 1px solid #a6d4ff;
			border-radius: 8px;
			color: var(--primary-color);
			margin-bottom: 28px;
			transition: all 0.36s;

			&-text {
				margin-top: 4px;
				font-weight: 600;
			}
		}

		&-infoActive {
			background-color: #e5f5ff;
			border-color: #7dbcff;
		}
	}

	.popup {
		width: 100%;
		box-sizing: border-box;

		&-options {
			width: 100%;
			padding: 12px 10px;
			box-sizing: border-box;
			display: flex;
			justify-content: space-between;
		}

		&-content {
			max-height: 60vh;
			overflow: auto;
			padding: 20px 26px;
			display: flex;
			flex-direction: column;
			gap: 6px 0;
			background-color: var(--background-color);
		}

		&-btn {
			&-danger {
				color: #d45050;
			}

			&-primary {
				color: var(--primary-color);
			}
		}
	}
</style>